<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>26 简易实例 Observable(一) · ShaofeiZi Blog · 做个日常记录</title>
    <meta name="description" content="訾绍飞的博客。万物皆有裂缝处，那是光射进来的地方。">
    <link rel="shortcut icon" href="/BLOG/favicon.ico">
  <link rel="manifest" href="/BLOG/manifest.json">
  <meta name="theme-color" content="#3F51B5">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <link rel="apple-touch-icon" href="/BLOG/icons/192.png">
  <link rel="mask-icon" href="/BLOG/icons/safari-pinned-tab.svg" color="#3eaf7c">
  <meta name="msapplication-TileImage" content="/icons/192.png">
  <meta name="msapplication-TileColor" content="#3F51B5">
    
    <link rel="preload" href="/BLOG/assets/css/42.styles.90045bd1.css" as="style"><link rel="preload" href="/BLOG/assets/js/app.1a725be8.js" as="script"><link rel="preload" href="/BLOG/assets/js/8.d9eebc06.js" as="script"><link rel="prefetch" href="/BLOG/assets/js/7.88ba0bb7.js"><link rel="prefetch" href="/BLOG/assets/js/0.d3e592bd.js"><link rel="prefetch" href="/BLOG/assets/js/1.39b9c99c.js"><link rel="prefetch" href="/BLOG/assets/js/2.68dc10c9.js"><link rel="prefetch" href="/BLOG/assets/js/3.dfebdd5e.js"><link rel="prefetch" href="/BLOG/assets/js/4.ea97a821.js"><link rel="prefetch" href="/BLOG/assets/js/5.d8c2ecbf.js"><link rel="prefetch" href="/BLOG/assets/js/6.e51cd79c.js"><link rel="prefetch" href="/BLOG/assets/js/9.1a541d13.js"><link rel="prefetch" href="/BLOG/assets/js/10.4ec9ca67.js"><link rel="prefetch" href="/BLOG/assets/js/11.02558377.js"><link rel="prefetch" href="/BLOG/assets/js/12.d0e2086f.js"><link rel="prefetch" href="/BLOG/assets/js/13.5af02ddd.js"><link rel="prefetch" href="/BLOG/assets/js/14.5d9fcbf2.js"><link rel="prefetch" href="/BLOG/assets/js/15.ca0178b2.js"><link rel="prefetch" href="/BLOG/assets/js/16.cd99d056.js"><link rel="prefetch" href="/BLOG/assets/js/17.56f11c1d.js"><link rel="prefetch" href="/BLOG/assets/js/18.21837cc7.js"><link rel="prefetch" href="/BLOG/assets/js/19.73335fea.js"><link rel="prefetch" href="/BLOG/assets/js/20.1632ab79.js"><link rel="prefetch" href="/BLOG/assets/js/21.43175244.js"><link rel="prefetch" href="/BLOG/assets/js/22.5b7c0cca.js"><link rel="prefetch" href="/BLOG/assets/js/23.e624ba97.js"><link rel="prefetch" href="/BLOG/assets/js/24.ac5f7b41.js"><link rel="prefetch" href="/BLOG/assets/js/25.6934a11d.js"><link rel="prefetch" href="/BLOG/assets/js/26.407b2583.js"><link rel="prefetch" href="/BLOG/assets/js/27.7449d673.js"><link rel="prefetch" href="/BLOG/assets/js/28.52e25437.js"><link rel="prefetch" href="/BLOG/assets/js/29.fba21f3a.js"><link rel="prefetch" href="/BLOG/assets/js/30.2cd6d3e2.js"><link rel="prefetch" href="/BLOG/assets/js/31.0b0a749f.js"><link rel="prefetch" href="/BLOG/assets/js/32.92134487.js"><link rel="prefetch" href="/BLOG/assets/js/33.ad2b89cc.js"><link rel="prefetch" href="/BLOG/assets/js/34.9b22334e.js"><link rel="prefetch" href="/BLOG/assets/js/35.825f3d75.js"><link rel="prefetch" href="/BLOG/assets/js/36.cc3da84c.js"><link rel="prefetch" href="/BLOG/assets/js/37.8f339f62.js"><link rel="prefetch" href="/BLOG/assets/js/38.5674618f.js"><link rel="prefetch" href="/BLOG/assets/js/39.180f0d85.js"><link rel="prefetch" href="/BLOG/assets/js/40.275f26e3.js"><link rel="prefetch" href="/BLOG/assets/js/41.ce0f5927.js">
    <link rel="stylesheet" href="/BLOG/assets/css/42.styles.90045bd1.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div data-app="true" id="app" class="application theme--light"><div class="application--wrap"><div class="v-progress-linear blog-progress" style="height:3px;display:none;"><div class="v-progress-linear__background accent" style="height:3px;opacity:0.4;width:100%;"></div><div class="v-progress-linear__bar"><!----><div class="v-progress-linear__bar__determinate accent" style="width:0%;"></div></div></div><aside class="v-navigation-drawer v-navigation-drawer--close v-navigation-drawer--fixed v-navigation-drawer--is-mobile" style="height:100%;margin-top:0px;max-height:calc(100% - 0px);transform:translateX(-240px);width:240px;"><div><div class="aside-brand-wrap"><div class="aside-brand"><a href="/BLOG/" class="aside-avatar elevation-2 router-link-active"><img src="/BLOG/face.png" alt="avatar"></a><hgroup class="mt-3 variant-hide"><div class="subheading white--text">訾绍飞</div><a href="mailto:zishaofei221@gmail.com" title="zishaofei221@gmail.com" class="aside-mail primary--text text--lighten-5">zishaofei221@gmail.com</a></hgroup></div></div><hr class="v-divider theme--dark"><div class="v-list nav-list"><div class="secondary--text"><a href="/BLOG/" class="v-list__tile v-list__tile--link"><div class="v-list__tile__avatar"><div class="v-avatar" style="height:40px;width:40px;"><i class="fa fa-home"></i></div></div><div class="v-list__tile__content">首页</div></a></div><div class="secondary--text"><a href="/BLOG/tags" class="v-list__tile v-list__tile--link"><div class="v-list__tile__avatar"><div class="v-avatar" style="height:40px;width:40px;"><i class="fa fa-tag"></i></div></div><div class="v-list__tile__content">标签</div></a></div><div class="secondary--text"><a href="https://github.com/ShaofeiZi" target="_blank" class="v-list__tile v-list__tile--link"><div class="v-list__tile__avatar"><div class="v-avatar" style="height:40px;width:40px;"><i class="fab fa-github"></i></div></div><div class="v-list__tile__content">Github</div></a></div><div class="secondary--text"><a href="/BLOG/about" class="v-list__tile v-list__tile--link"><div class="v-list__tile__avatar"><div class="v-avatar" style="height:40px;width:40px;"><i class="fa fa-user-secret"></i></div></div><div class="v-list__tile__content">About</div></a></div></div></div><div class="v-navigation-drawer__border"></div></aside><nav class="blog-toolbar v-toolbar v-toolbar--fixed theme--dark primary" style="margin-top:0px;padding-right:0px;padding-left:0px;transform:translateY(0px);"><div class="v-toolbar__content" style="height:56px;"><button type="button" class="v-btn v-btn--icon"><div class="v-btn__content"><i class="fa fa-bars"></i></div></button><div class="v-toolbar__title">26 简易实例 Observable(一)</div><div class="spacer"></div><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""><!----></div><div class="v-menu" style="display:none;"><div class="v-menu__activator"><button type="button" class="v-btn v-btn--icon"><div class="v-btn__content"><i class="fa fa-share-alt"></i></div></button></div><div class="v-menu__content" style="max-height:auto;min-width:0px;max-width:auto;top:12px;left:0px;transform-origin:top right;z-index:0;display:none;"><div class="v-list"><div class="secondary--text"><a class="v-list__tile v-list__tile--link"><div class="v-list__tile__avatar"><div class="v-avatar" style="height:40px;width:40px;"><i class="fa fa-lg fa-copy"></i></div></div><div class="v-list__tile__title">复制链接</div></a></div></div><input type="text" tabindex="-1" aria-hidden="true" value="" class="fake-hide"></div></div></div></nav><main class="v-content" style="padding-top:56px;padding-right:0px;padding-bottom:0px;padding-left:0px;"><div class="v-content__wrap"><div class="container blog-container grid-list-xl align-center"><div class="layout row wrap"><div class="flex mb-3 xs12"><article class="v-card elevation-16 post-card" style="height:undefined;"><div class="v-card__title"><div class="flex xs12"><h2 class="display-1 mb-3">26 简易实例 Observable(一)</h2><div class="post-meta"><time datetime="2018-04-29T12:16:18.000Z" class="secondary--text post-time">2018年04月29日</time></div></div></div><div class="v-card__text pt-0 pb-0"><div class="flex xs12"><div class="content custom"><h1 id="_30-天精通-rxjs-26-：简易实例-observable-一"><a href="#_30-天精通-rxjs-26-：简易实例-observable-一" aria-hidden="true" class="header-anchor">#</a> 30 天精通 RxJS(26)：简易实例 Observable(一)</h1><p>因为实在太多读者在问要如何使用 Observable，所以特别调整了本系列文章最后几篇的内容，空出一天的位置来写如何简易实现 Observable。</p><p>为什么是简易实例而不完整实例呢？ 当然这个系列的文章是希望读者能学会如何使用 RxJS，而 实使用 Observable 其实只是帮助我们理解 Observable 的运作方式，所以这篇文章会尽可能地简单，一来让读者容易理解及吸收，二来有兴趣的读者可以再沿着这篇文章的内容去完整的实现。
</p><h2 id="重点观念"><a href="#重点观念" aria-hidden="true" class="header-anchor">#</a> 重点观念</h2><p>Observable 跟 Observer Pattern 是不同的，Observable 内部并没有管理一份订阅清单，<strong>订阅 Observable 就像是执行一个 function 一样</strong>！</p><p>所以实现过程的重点</p><ul><li>订阅就是执行一个 funciton</li><li>订阅接收的实例具备 next, error, complete 三个方法</li><li>订阅会返回一个可退订(unsubscribe)的实例</li></ul><h2 id="基本-observable-实现"><a href="#基本-observable-实现" aria-hidden="true" class="header-anchor">#</a> 基本 observable 实现</h2><p>先用最简单的 function 来建立 observable 实例</p><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">create</span><span class="token punctuation">(</span>subscriber<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> observable <span class="token operator">=</span> <span class="token punctuation">{</span>
        subscribe<span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token function">subscriber</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span>
        <span class="token punctuation">}</span>       
    <span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> observable<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

</code></pre><p>上面这段代码就可以做最简单的订阅，像下面这样</p><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">create</span><span class="token punctuation">(</span>subscriber<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">var</span> observable <span class="token operator">=</span> <span class="token punctuation">{</span>
        subscribe<span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token function">subscriber</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span>
        <span class="token punctuation">}</span>       
    <span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> observable<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">var</span> observable <span class="token operator">=</span> <span class="token function">create</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token keyword">var</span> observer <span class="token operator">=</span> <span class="token punctuation">{</span>
  next<span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

observable<span class="token punctuation">.</span><span class="token function">subscribe</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span>
<span class="token comment">// 1</span>
<span class="token comment">// 2</span>
<span class="token comment">// 3</span>

</code></pre><p><a href="https://jsbin.com/tububez/1/edit?js,console" target="_blank" rel="noopener noreferrer">JSBin</a></p><p>这时我们已经有最简单的功能了，但这里有一个大问题，就是 observable 在结束(complete)就不应该再发送元素</p><pre class="language-javascript"><code><span class="token keyword">var</span> observable <span class="token operator">=</span> <span class="token function">create</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">complete</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token string">'still work'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token keyword">var</span> observer <span class="token operator">=</span> <span class="token punctuation">{</span>
  next<span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  complete<span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'complete!'</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

observable<span class="token punctuation">.</span><span class="token function">subscribe</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span>
<span class="token comment">// 1</span>
<span class="token comment">// 2</span>
<span class="token comment">// 3</span>
<span class="token comment">// &quot;complete!&quot;</span>
<span class="token comment">// &quot;still work&quot;</span>

</code></pre><p><a href="https://jsbin.com/tububez/2/edit?js,console" target="_blank" rel="noopener noreferrer">JSBin</a></p><p>从上面的代码可以看到 complete 之后还是能送元素出来，另外还有一个问题就是 observer，如果是不完整的就会出错，这也不是我们希望看到的。</p><pre class="language-javascript"><code><span class="token keyword">var</span> observable <span class="token operator">=</span> <span class="token function">create</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">complete</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// error: complete is not a function </span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token keyword">var</span> observer <span class="token operator">=</span> <span class="token punctuation">{</span>
  next<span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

observable<span class="token punctuation">.</span><span class="token function">subscribe</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span>
<span class="token comment">// 1</span>
<span class="token comment">// 2</span>
<span class="token comment">// 3</span>
<span class="token comment">// &quot;complete!&quot;</span>
<span class="token comment">// &quot;still work&quot;</span>

</code></pre><p><a href="https://jsbin.com/tububez/3/edit?js,console" target="_blank" rel="noopener noreferrer">JSBin</a></p><p>上面这段代码可以看出来，当使用者 observer 实例没有 complete 方法时，就会报错。
我们应该修正这两个问题！</p><h2 id="实现简易-observer"><a href="#实现简易-observer" aria-hidden="true" class="header-anchor">#</a> 实现简易 Observer</h2><p>要修正这两个问题其实并不难，我们只要实现一个 Observer 的类别，每次使用者传入的 observer 都会利用这个类别转乘我们想要 Observer 实例。</p><p>首先订阅时有可能传入一个 observer 实例，或是一到三个 function(next, error, complete)，所以我们要建立一个类别可以接受各种可能的参数</p><pre class="language-javascript"><code><span class="token keyword">class</span> <span class="token class-name">Observer</span> <span class="token punctuation">{</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span>destinationOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">switch</span> <span class="token punctuation">(</span>arguments<span class="token punctuation">.</span>length<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">case</span> <span class="token number">0</span><span class="token punctuation">:</span>
        <span class="token comment">// 空的 observer</span>
      <span class="token keyword">case</span> <span class="token number">1</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>destinationOrNext<span class="token punctuation">)</span> <span class="token punctuation">{</span>
          <span class="token comment">// 空的 observer</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">typeof</span> destinationOrNext <span class="token operator">===</span> <span class="token string">'object'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
          <span class="token comment">// 传入了 observer 实例</span>
        <span class="token punctuation">}</span>
      <span class="token keyword">default</span><span class="token punctuation">:</span>
        <span class="token comment">// 如果上面都不是，代表应该是传入了一到三个 function</span>
        <span class="token keyword">break</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

</code></pre><p>写一个方法(safeObserver)来回传正常的 observer</p><pre class="language-javascript"><code><span class="token keyword">class</span> <span class="token class-name">Observer</span> <span class="token punctuation">{</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span>destinationOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// ... 一些代码</span>
  <span class="token punctuation">}</span>
  <span class="token function">safeObserver</span><span class="token punctuation">(</span>observerOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">let</span> next<span class="token punctuation">;</span>

    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">typeof</span> <span class="token punctuation">(</span>observerOrNext<span class="token punctuation">)</span> <span class="token operator">===</span> <span class="token string">'function'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// observerOrNext 是 next function</span>
      next <span class="token operator">=</span> observerOrNext<span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>observerOrNext<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// observerOrNext 是 observer 实例</span>
      next <span class="token operator">=</span> observerOrNext<span class="token punctuation">.</span>next <span class="token operator">||</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
      error <span class="token operator">=</span> observerOrNext<span class="token punctuation">.</span>error <span class="token operator">||</span> <span class="token keyword">function</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token punctuation">{</span> 
        <span class="token keyword">throw</span> err 
      <span class="token punctuation">}</span><span class="token punctuation">;</span>
      complete <span class="token operator">=</span> observerOrNext<span class="token punctuation">.</span>complete <span class="token operator">||</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token comment">// 最后回传我们预期的 observer 实例</span>
    <span class="token keyword">return</span> <span class="token punctuation">{</span>
      next<span class="token punctuation">:</span> next<span class="token punctuation">,</span>
      error<span class="token punctuation">:</span> error<span class="token punctuation">,</span>
      complete<span class="token punctuation">:</span> complete
    <span class="token punctuation">}</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

</code></pre><p>再把 constructor 完成</p><pre class="language-javascript"><code><span class="token comment">// 预设空的 observer </span>
<span class="token keyword">const</span> emptyObserver <span class="token operator">=</span> <span class="token punctuation">{</span>
  next<span class="token punctuation">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
  error<span class="token punctuation">:</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span> <span class="token keyword">throw</span> err<span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">,</span>
  complete<span class="token punctuation">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">class</span> <span class="token class-name">Observer</span> <span class="token punctuation">{</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span>destinationOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">switch</span> <span class="token punctuation">(</span>arguments<span class="token punctuation">.</span>length<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">case</span> <span class="token number">0</span><span class="token punctuation">:</span>
        <span class="token comment">// 空的 observer</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>destination <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">safeObserver</span><span class="token punctuation">(</span>emptyObserver<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">break</span><span class="token punctuation">;</span>
      <span class="token keyword">case</span> <span class="token number">1</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>destinationOrNext<span class="token punctuation">)</span> <span class="token punctuation">{</span>
          <span class="token comment">// 空的 observer</span>
          <span class="token keyword">this</span><span class="token punctuation">.</span>destination <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">safeObserver</span><span class="token punctuation">(</span>emptyObserver<span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token keyword">break</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">typeof</span> destinationOrNext <span class="token operator">===</span> <span class="token string">'object'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
          <span class="token comment">// 传入了 observer 实例</span>
          <span class="token keyword">this</span><span class="token punctuation">.</span>destination <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">safeObserver</span><span class="token punctuation">(</span>destinationOrNext<span class="token punctuation">)</span><span class="token punctuation">;</span>
          <span class="token keyword">break</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
      <span class="token keyword">default</span><span class="token punctuation">:</span>
        <span class="token comment">// 如果上面都不是，代表应该是传入了一到三个 function</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>destination <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">safeObserver</span><span class="token punctuation">(</span>destinationOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">break</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
  <span class="token function">safeObserver</span><span class="token punctuation">(</span>observerOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// ... 一些代码</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

</code></pre><p><a href="https://jsbin.com/tububez/5/edit?js,console" target="_blank" rel="noopener noreferrer">JSBin</a></p><p>这里我们把真正的 observer 塞到 <code>this.destination</code>，接着完成 observer 的方法。</p><p>Observer 的三个主要的方法(next, error, complete)都应该结束或退订后不能再被执行，所以我们在实例内部偷塞一个 boolean 值来作为是否曾经结束的依据。</p><pre class="language-javascript"><code><span class="token keyword">class</span> <span class="token class-name">Observer</span> <span class="token punctuation">{</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span>destinationOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// ... 一些代码</span>
  <span class="token punctuation">}</span>
  <span class="token function">safeObserver</span><span class="token punctuation">(</span>observerOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// ... 一些代码</span>
  <span class="token punctuation">}</span>
  <span class="token function">unsubscribe</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>isStopped <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span> <span class="token comment">// 偷塞一个属性 isStopped</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

</code></pre><p>接着要实现三个主要的方法就很简单了，只要先判断 <code>isStopped</code> 在使用 <code>this.destination</code> 实例来传送值就可以了</p><pre class="language-javascript"><code><span class="token keyword">class</span> <span class="token class-name">Observer</span> <span class="token punctuation">{</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span>destinationOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// ... 一些代码</span>
  <span class="token punctuation">}</span>
  <span class="token function">safeObserver</span><span class="token punctuation">(</span>observerOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// ... 一些代码</span>
  <span class="token punctuation">}</span>

  <span class="token function">next</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token keyword">this</span><span class="token punctuation">.</span>isStopped <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>next<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 先判断是否停止过</span>
      <span class="token keyword">try</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>destination<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 传送值</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">err</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">unsubscribe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">throw</span> err<span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

  <span class="token function">error</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token keyword">this</span><span class="token punctuation">.</span>isStopped <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>error<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 先判断是否停止过</span>
      <span class="token keyword">try</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>destination<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 传送错误</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">anotherError</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">unsubscribe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">throw</span> anotherError<span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">unsubscribe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

  <span class="token function">complete</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token keyword">this</span><span class="token punctuation">.</span>isStopped <span class="token operator">&amp;&amp;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>complete<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 先判断是否停止过</span>
      <span class="token keyword">try</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>destination<span class="token punctuation">.</span><span class="token function">complete</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 发送停止讯息</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">err</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">unsubscribe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">throw</span> err<span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">unsubscribe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 发送停止讯息后退订</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>

  <span class="token function">unsubscribe</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>isStopped <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

</code></pre><p><a href="https://jsbin.com/tububez/6/edit?js,console" target="_blank" rel="noopener noreferrer">JSBin</a></p><p>到这里我们就完成基本的 Observer 实现了，接着让我们拿到基本版的 observable 中使用吧。</p><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">create</span><span class="token punctuation">(</span>subscriber<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> observable <span class="token operator">=</span> <span class="token punctuation">{</span>
        subscribe<span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span>observerOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">const</span> realObserver <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Observer</span><span class="token punctuation">(</span>observerOrNext<span class="token punctuation">,</span> error<span class="token punctuation">,</span> complete<span class="token punctuation">)</span>
            <span class="token function">subscriber</span><span class="token punctuation">(</span>realObserver<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> realObserver<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>       
    <span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> observable<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">var</span> observable <span class="token operator">=</span> <span class="token function">create</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">complete</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  observer<span class="token punctuation">.</span><span class="token function">next</span><span class="token punctuation">(</span><span class="token string">'not work'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token keyword">var</span> observer <span class="token operator">=</span> <span class="token punctuation">{</span>
  next<span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  complete<span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'complete!'</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

observable<span class="token punctuation">.</span><span class="token function">subscribe</span><span class="token punctuation">(</span>observer<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 1</span>
<span class="token comment">// 2</span>
<span class="token comment">// 3</span>
<span class="token comment">// complete!</span>

</code></pre><p><a href="https://jsbin.com/tububez/7/edit?js,console" target="_blank" rel="noopener noreferrer">JSBin</a></p><p>到这里我们就完成最基本的 observable 了，至少基本的行为都跟我们期望的一致，我知道读者们仍然不会放过我，你们会希望做出一个 Observable 型别以及至少一个 operator 对吧？ 不用担心，我们下一篇就会讲解如何建立一个 Observable 型别和 operator 的方法！</p><h2 id="今日小结"><a href="#今日小结" aria-hidden="true" class="header-anchor">#</a> 今日小结</h2><p>今天我们复习了 Observable 的重要概念，并用这些重要的概念实现出了基本的 observable 以及 Observer 的类别。</p><p>不知道今天读者们有没有收获呢？ 如果有任何问题，欢迎在下方留言给我，谢谢！</p></div></div></div><div class="v-card__actions"><div class="flex xs12"><a href="/BLOG/tags/RXJS"><span tabindex="0" class="v-chip capitalize chip-tag v-chip--label v-chip--small"><span class="v-chip__content">RXJS</span></span></a></div></div></article></div><div class="flex text-xs-left xs6"><a href="/BLOG/posts/rxjs27.html" class="post-nav v-btn v-btn--flat v-btn--router"><div class="v-btn__content"><div class="grey--text"><i class="fa mr-1 fa-chevron-left"></i>Prev</div><div class="title mt-1 primary--text hidden-xs-only">27 简易实现 Observable(二)</div></div></a></div><div class="flex text-xs-right xs6"><a href="/BLOG/posts/rxjs25.html" class="post-nav v-btn v-btn--flat v-btn--router"><div class="v-btn__content"><div class="grey--text">Next
          <i class="fa ml-1 fa-chevron-right"></i></div><div class="title mt-1 primary--text hidden-xs-only">25 ：Subject 总结</div></div></a></div><div class="flex mt-3 xs12"><div class="v-card" style="height:undefined;"><div class="v-card__title"><span class="headline">Comment</span></div></div></div></div></div><footer class="v-footer blog-footer darken-1 mt-3 theme--dark" style="height:auto;"><div class="primary--text text--lighten-4 text-xs-center py-3 v-card v-card--flat v-card--tile primary" style="height:undefined;"><div class="v-card__text pb-0">博客内容遵循 <a rel="license noopener noreferrer" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></div><div class="v-card__text pt-0 mt-1"><span>訾绍飞 © 2015 - 2018</span><span><!---->
        Power by
        <a href="https://vuepress.vuejs.org" target="_blank" rel="noopener noreferrer">VuePress</a> Theme
        <a href="https://github.com/ShaofeiZi/BLOG" target="_blank" rel="noopener noreferrer">indigo</a></span></div></div></footer></div></main><button type="button" class="v-btn v-btn--bottom v-btn--floating v-btn--fixed v-btn--right accent" style="display:none;"><div class="v-btn__content"><i class="fa fa-lg fa-chevron-up"></i></div></button></div></div></div>
    <script src="/BLOG/assets/js/8.d9eebc06.js" defer></script><script src="/BLOG/assets/js/app.1a725be8.js" defer></script>
  </body>
</html>
